//
//  CheckMoreController.m
//  HappyBaby
//
//  Created by lanou on 15/11/26.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "CheckMoreController.h"
#import "CheckMoreCell.h"
#import "CheckMoreModel.h"
#import "Define.h"
#import "MJRefresh.h"
#import "DetailController.h"

@interface CheckMoreController () <UITableViewDataSource, UITableViewDelegate>

//@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *modelArray;

@end

@implementation CheckMoreController
- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 注册cell
    [self.tableView registerClass:[CheckMoreCell class] forCellReuseIdentifier:@"CheckCell"];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    // 趣学：http://api.bbwansha.com:8080/v22/index.php/Home/theme/detail?userid=0&page=1&themeid=80&age=-1 请求链接
    // section1：http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/suggestion?userid=0&page=0&age=0
    // section2：
    
    // 亲子游戏：http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/category?userid=0&categoryid=1&accesstoken=&page=1&age=-1
    // 玩具：http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/category?userid=0&categoryid=2&accesstoken=&page=1&age=-1
    // 童书：http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/category?userid=0&categoryid=3&accesstoken=&page=1&age=-1
    
    NSString *urlStr = nil;
    
    if (_category_id > 0 && _category_id < 4){
        
        // 如果_category_id在0~4之间（不包含0和4）就说明师点击分类Button来的，修改tableView的frame
        self.tableView.frame = CGRectMake(0, 35*kScaleY, self.view.width, self.view.height - 35 * kScaleY);
        
        urlStr = [NSString stringWithFormat:@"http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/category?userid=0&categoryid=%d&accesstoken=&page=1&age=-1",_category_id];
    } else if (_section == 0) {
        urlStr = @"http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/suggestion?userid=0&page=0&age=0";
        self.navigationItem.title = @"今天玩儿啥";
        
    } else if (_section == 1) {
        urlStr = @"http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/tag?userid=0&tagid=304&accesstoken=&page=1&age=-1";
        self.navigationItem.title = @"随手玩儿啥";
        
    }else  if (self.fancinatingModel) {
        // 如果是从趣玩界面跳过来的，使用下面的链接
        urlStr = [NSString stringWithFormat:@"http://api.bbwansha.com:8080/v22/index.php/Home/theme/detail?userid=0&page=1&themeid=%@&age=-1",self.fancinatingModel.theme_id];
        self.navigationItem.title = self.fancinatingModel.theme_title;
    }
    
    
    
    
    NSURL *url = [NSURL URLWithString:urlStr];
    if (url) {
        // 请求解析数据
        [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *dataArray = [dic objectForKey:@"data"];
            for (NSDictionary *modelDic in dataArray) {
                CheckMoreModel *model = [[CheckMoreModel alloc] init];
                [model setValuesForKeysWithDictionary:modelDic];
                [self.modelArray addObject:model];
            }
            dispatch_sync(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            
        }] resume];
    }
    
    
    // 上提加载更多
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreRefresh)];
}





- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.modelArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CheckMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CheckCell" forIndexPath:indexPath];
    
    CheckMoreModel *model = self.modelArray[indexPath.section];
    cell.model = model;

    return cell;
}



- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200 * kScaleY;
    
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 20 * kScaleY;
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1*kScaleY;
}

// 选中cell的方法
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    DetailController *detailVc = [[DetailController alloc] init];
    CheckMoreModel *model = self.modelArray[indexPath.section];
    detailVc.checkMoreModel = model;
    [self.navigationController pushViewController:detailVc animated:YES];
}

#pragma mark --上提加载更多
- (void) loadMoreRefresh
{
    // 请求链接 http://api.bbwansha.com:8080/v22/index.php/Home/theme/detail?userid=0&page=1&themeid=80&age=-1
    static int page = 1;
    
    NSString *urlStr = [NSString stringWithFormat:@"http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/suggestion?userid=0&page=%d&age=0",page];
    if (self.fancinatingModel) {
        urlStr = [NSString stringWithFormat:@"http://api.bbwansha.com:8080/v22/index.php/Home/theme/detail?userid=0&page=%d&themeid=%@&age=-1",page,self.fancinatingModel.theme_id];
    }
    
    NSURL *url = [NSURL URLWithString:urlStr];
    [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //解析数据
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *dataArray = [dic objectForKey:@"data"];
        for (NSDictionary *modelDic in dataArray) {
            CheckMoreModel *model = [[CheckMoreModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.modelArray addObject:model];
        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        // 结束刷新
        [self.tableView.footer endRefreshing];
    }]resume];
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
